package com.cloudfun.campusshare.util;

import lombok.SneakyThrows;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;

/**
 * Created by Huqin on 2020/7/31
 */
public class NetUtil {

    private NetUtil() {
    }

    /**
     * 获取客户端ip地址
     *
     * @param request
     * @return
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取本机ip
     *
     * @return
     */
    public static String getLocalIp() {
        Optional<String> optional = getLocalIPList().stream().findFirst();
        return optional.orElse(null);
    }

    /**
     * 获取本机ip
     *
     * @return
     */
    @SneakyThrows
    public static List<String> getLocalIPList() {
        List<String> ipList = new ArrayList<>();
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        NetworkInterface networkInterface;
        Enumeration<InetAddress> inetAddresses;
        InetAddress inetAddress;
        String ip;
        while (networkInterfaces.hasMoreElements()) {
            networkInterface = networkInterfaces.nextElement();
            inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                inetAddress = inetAddresses.nextElement();
                // IPV4、非环回
                if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                    ip = inetAddress.getHostAddress();
                    ipList.add(ip);
                }
            }
        }
        return ipList;
    }

}
